package t4tools.lepath.util;

import java.util.HashMap;
import java.util.Map;

import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;

import t4tools.lepath.model.Field;

public final class GeneratorUtil {
	public static final Map<String, String> PRIMITIVE_TYPES;
	
	static {
		PRIMITIVE_TYPES = new HashMap<>();
		PRIMITIVE_TYPES.put("Z", Type.getInternalName(Boolean.class));
		PRIMITIVE_TYPES.put("C", Type.getInternalName(Character.class));
		PRIMITIVE_TYPES.put("B", Type.getInternalName(Byte.class));
		PRIMITIVE_TYPES.put("S", Type.getInternalName(Short.class));
		PRIMITIVE_TYPES.put("I", Type.getInternalName(Integer.class));
		PRIMITIVE_TYPES.put("F", Type.getInternalName(Float.class));
		PRIMITIVE_TYPES.put("J", Type.getInternalName(Long.class));
		PRIMITIVE_TYPES.put("D", Type.getInternalName(Double.class));
	}
	
	public static void boxPrimitive(MethodVisitor mv, Field field) {
		String wrapperInternal = PRIMITIVE_TYPES.get(field.getTypeDescr());
		if (Util.notEmpty(wrapperInternal)) {
			mv.visitMethodInsn(Opcodes.INVOKESTATIC, wrapperInternal, "valueOf", "(" + field.getTypeDescr() + ")L" + wrapperInternal + ";");
		}
	}
	
	public static void addDefaultConstruct(ClassWriter writer) {
		MethodVisitor mv = writer.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
		mv.visitCode();
		mv.visitVarInsn(Opcodes.ALOAD, 0);
		mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V");
		mv.visitInsn(Opcodes.RETURN);
		mv.visitMaxs(1, 1);
		mv.visitEnd();
	}
}
